package com.alex.mq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

//@Configuration
public class RabbitMQConsumerConfig {

    @Bean
    public Exchange exchange() {
        return new DirectExchange("mall.order", true, false, new HashMap<>());
    }

    @Bean
    public Queue queue() {
        return new Queue("mall.order.add", true, false, false, new HashMap<>());
    }

    @Bean
    public Binding binding() {
        return new Binding("mall.order.add", Binding.DestinationType.QUEUE,
                "mall.order", "add", new HashMap<>());
    }

    @Bean
    public MessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames("mall.order.add");

        // 设置并发消费数
        container.setConcurrentConsumers(5);
        container.setMaxConcurrentConsumers(10);

        Map<String, Object> argumentMap = new HashMap<>();
        container.setConsumerArguments(argumentMap);
        container.setConsumerTagStrategy((item) -> "订单系统ADD逻辑消费者" + item);

        container.setMessageListener((message -> {
            try {
                System.out.println("message body: " + new String(message.getBody(), "UTF-8"));
                System.out.println("message properties: " + message.getMessageProperties());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }));

        return container;
    }
}
